<template>
    <div class="option-panel">
        <el-tabs v-model="activeName" class="config-tabs">
            <el-tab-pane label="基础配置" name="basic">
                <div class="config-section" >
                    <el-form label-position="top" >
                        <el-form-item label="演示模式">
                            <el-switch v-model="chartConfig.isDemo" @change="val => updateField('isDemo', val)" />
                            <div class="demo-tip">开启后将使用测试数据</div>
                        </el-form-item>
                        
                        <el-form-item label="图表标题">
                            <el-input v-model="chartConfig.title" @change="val => updateField('title', val)" placeholder="请输入图表标题" />
                        </el-form-item>
                        
                        <el-form-item label="显示标题栏">
                            <el-switch v-model="chartConfig.showTitle" @change="val => updateField('showTitle', val)" />
                        </el-form-item>
                        
                        <el-form-item label="显示图例">
                            <el-switch v-model="chartConfig.showLegend" @change="val => updateField('showLegend', val)" />
                        </el-form-item>
                        
                        <el-form-item label="显示数值">
                            <el-switch v-model="chartConfig.showValue" @change="val => updateField('showValue', val)" />
                        </el-form-item>
                        
                        <el-form-item label="数值格式">
                            <el-select v-model="chartConfig.valueFormat" @change="val => updateField('valueFormat', val)" placeholder="选择数值格式">
                                <el-option label="数字" value="number" />
                                <el-option label="百分比" value="percent" />
                                <el-option label="货币" value="currency" />
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="数值精度">
                            <el-input-number v-model="chartConfig.precision" :min="0" :max="10" @change="val => updateField('precision', val)" />
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
            
            <el-tab-pane label="数据配置" name="data">
                <div class="config-section">
                    <el-form label-position="top">
                        <el-form-item label="分类数据">
                            <el-input 
                                v-model="chartConfig.categories" 
                                type="textarea" 
                                :rows="4"
                                placeholder="请输入分类数据，用逗号分隔，例如：1月,2月,3月,4月,5月,6月"
                                @change="val => updateField('categories', val)"
                            />
                        </el-form-item>
                        
                        <el-form-item label="系列数据">
                            <el-input 
                                v-model="chartConfig.series" 
                                type="textarea" 
                                :rows="6"
                                placeholder="请输入系列数据，JSON格式"
                                @change="val => updateField('series', val)"
                            />
                            <div class="data-tip">
                                <el-button size="small" @click="loadExampleData">加载示例数据</el-button>
                                <div class="example-format">
                                    格式示例：<br/>
                                    [{"name":"销售额","data":[120,200,150,80,70,110],"color":"#409eff"},<br/>
                                    {"name":"利润","data":[20,40,30,15,12,25],"color":"#67c23a"}]
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
            
            <el-tab-pane label="样式配置" name="style">
                <div class="config-section">
                    <el-form label-position="top">
                        <el-form-item label="主题色">
                            <el-color-picker v-model="chartConfig.themeColor" @change="val => updateField('themeColor', val)" />
                        </el-form-item>
                        
                        <el-form-item label="柱状图颜色">
                            <div class="color-list">
                                <el-color-picker 
                                    v-for="(color, index) in chartConfig.colors" 
                                    :key="index"
                                    v-model="chartConfig.colors[index]"
                                    @change="val => updateField('colors', chartConfig.colors)"
                                />
                                <el-button size="small" @click="addColor">添加颜色</el-button>
                            </div>
                        </el-form-item>
                        
                        <el-form-item label="柱状图宽度">
                            <el-slider v-model="chartConfig.barWidth" :min="10" :max="100" @change="val => updateField('barWidth', val)" />
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
            
            <el-tab-pane label="高级配置" name="advanced">
                <div class="config-section">
                    <el-form label-position="top">
                        <el-form-item label="自定义配置">
                            <el-input 
                                v-model="chartConfig.customOption" 
                                type="textarea" 
                                :rows="8"
                                placeholder="请输入自定义 ECharts 配置，JSON格式"
                                @change="val => updateField('customOption', val)"
                            />
                            <div class="data-tip">
                                <el-button size="small" @click="loadExampleOption">加载示例配置</el-button>
                                <div class="example-format">
                                    可以自定义 grid、tooltip、axis 等配置<br/>
                                    示例：{"grid":{"left":"10%","right":"10%"}}
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
  
<script lang="ts" setup>
import { watch, ref, onBeforeUnmount, onMounted } from 'vue'

interface Props {
  isDemo?: boolean
  title?: string
  showTitle?: boolean
  showLegend?: boolean
  showValue?: boolean
  valueFormat?: string
  precision?: number
  categories?: string | string[]
  series?: string | any[]
  themeColor?: string
  colors?: string[] | string
  barWidth?: number | string
  customOption?: string | object
  [key: string]: any
}

const props = defineProps<Props>()
const emit = defineEmits(['config-change'])

const activeName = ref('basic')

const chartConfig = ref<{ [key: string]: any }>({
  isDemo: typeof props.isDemo === 'boolean' ? props.isDemo : false,
  title: typeof props.title === 'string' ? props.title : '',
  showTitle: typeof props.showTitle === 'boolean' ? props.showTitle : true,
  showLegend: typeof props.showLegend === 'boolean' ? props.showLegend : true,
  showValue: typeof props.showValue === 'boolean' ? props.showValue : false,
  valueFormat: ['number', 'percent', 'currency'].includes(props.valueFormat as string) ? props.valueFormat : 'number',
  precision: typeof props.precision === 'number' && !isNaN(props.precision!) ? props.precision : 2,
  categories: Array.isArray(props.categories) ? props.categories.join(',') : typeof props.categories === 'string' ? props.categories : '',
  series: Array.isArray(props.series) ? JSON.stringify(props.series, null, 2) : typeof props.series === 'string' ? props.series : '',
  themeColor: typeof props.themeColor === 'string' ? props.themeColor : '#409eff',
  colors: Array.isArray(props.colors) ? [...props.colors] : typeof props.colors === 'string' ? props.colors.split(',').map((s: string) => s.trim()).filter((s: string) => s) : ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399'],
  barWidth: typeof props.barWidth === 'number' && !isNaN(props.barWidth as number) ? props.barWidth : typeof props.barWidth === 'string' && !isNaN(parseFloat(props.barWidth)) ? parseFloat(props.barWidth) : 50,
  customOption: typeof props.customOption === 'object' && props.customOption !== null ? JSON.stringify(props.customOption, null, 2) : typeof props.customOption === 'string' ? props.customOption : ''
})

const addColor = () => {
  chartConfig.value.colors.push('#409eff');
  updateField('colors', chartConfig.value.colors);
}

const loadExampleData = () => {
  chartConfig.value.categories = '1月,2月,3月,4月,5月,6月'
  chartConfig.value.series = JSON.stringify([
    {
      name: '销售额',
      data: [120, 200, 150, 80, 70, 110],
      color: '#409eff'
    },
    {
      name: '利润',
      data: [20, 40, 30, 15, 12, 25],
      color: '#67c23a'
    }
  ], null, 2)
  updateField('categories',  chartConfig.value.categories);
  updateField('series',  chartConfig.value.series);
}

const loadExampleOption = () => {
  chartConfig.value.customOption = JSON.stringify({
    grid: {
      left: '10%',
      right: '10%'
    }
  }, null, 2)
  updateField('customOption', chartConfig.value.customOption)
}

const updateField = (key: string, value: any) => {
  emit('config-change', { key, value });
}

// 监听 props 字段变化，初始化配置
watch(
  () => ({ ...props }),
  (newProps) => {
    chartConfig.value.isDemo = typeof newProps.isDemo === 'boolean' ? newProps.isDemo : false;
    chartConfig.value.title = typeof newProps.title === 'string' ? newProps.title : '';
    chartConfig.value.showTitle = typeof newProps.showTitle === 'boolean' ? newProps.showTitle : true;
    chartConfig.value.showLegend = typeof newProps.showLegend === 'boolean' ? newProps.showLegend : true;
    chartConfig.value.showValue = typeof newProps.showValue === 'boolean' ? newProps.showValue : false;
    chartConfig.value.valueFormat = ['number', 'percent', 'currency'].includes(newProps.valueFormat as string) ? newProps.valueFormat : 'number';
    chartConfig.value.precision = typeof newProps.precision === 'number' && !isNaN(newProps.precision!) ? newProps.precision : 2;
    chartConfig.value.categories = Array.isArray(newProps.categories)
      ? newProps.categories.join(',')
      : typeof newProps.categories === 'string'
        ? newProps.categories
        : '';
    chartConfig.value.series = Array.isArray(newProps.series)
      ? JSON.stringify(newProps.series, null, 2)
      : typeof newProps.series === 'string'
        ? newProps.series
        : '';
    chartConfig.value.themeColor = typeof newProps.themeColor === 'string' ? newProps.themeColor : '#409eff';
    chartConfig.value.colors = Array.isArray(newProps.colors)
      ? [...newProps.colors]
      : typeof newProps.colors === 'string'
        ? newProps.colors.split(',').map((s: string) => s.trim()).filter((s: string) => s)
        : ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399'];
    chartConfig.value.barWidth = typeof newProps.barWidth === 'number' && !isNaN(newProps.barWidth as number)
      ? newProps.barWidth
      : typeof newProps.barWidth === 'string' && !isNaN(parseFloat(newProps.barWidth))
        ? parseFloat(newProps.barWidth)
        : 50;
    chartConfig.value.customOption = typeof newProps.customOption === 'object' && newProps.customOption !== null
      ? JSON.stringify(newProps.customOption, null, 2)
      : typeof newProps.customOption === 'string'
        ? newProps.customOption
        : '';
  },
  { immediate: true, deep: true }
)

onBeforeUnmount(() => {})

onMounted(() => {
  // 初始化赋值
  chartConfig.value.isDemo = typeof props.isDemo === 'boolean' ? props.isDemo : false;
  chartConfig.value.title = typeof props.title === 'string' ? props.title : '';
  chartConfig.value.showTitle = typeof props.showTitle === 'boolean' ? props.showTitle : true;
  chartConfig.value.showLegend = typeof props.showLegend === 'boolean' ? props.showLegend : true;
  chartConfig.value.showValue = typeof props.showValue === 'boolean' ? props.showValue : false;
  chartConfig.value.valueFormat = ['number', 'percent', 'currency'].includes(props.valueFormat as string) ? props.valueFormat : 'number';
  chartConfig.value.precision = typeof props.precision === 'number' && !isNaN(props.precision!) ? props.precision : 2;
  chartConfig.value.categories = Array.isArray(props.categories)
    ? props.categories.join(',')
    : typeof props.categories === 'string'
      ? props.categories
      : '';
  chartConfig.value.series = Array.isArray(props.series)
    ? JSON.stringify(props.series, null, 2)
    : typeof props.series === 'string'
      ? props.series
      : '';
  chartConfig.value.themeColor = typeof props.themeColor === 'string' ? props.themeColor : '#409eff';
  chartConfig.value.colors = Array.isArray(props.colors)
    ? [...props.colors]
    : typeof props.colors === 'string'
      ? props.colors.split(',').map((s: string) => s.trim()).filter((s: string) => s)
      : ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399'];
  chartConfig.value.barWidth = typeof props.barWidth === 'number' && !isNaN(props.barWidth as number)
    ? props.barWidth
    : typeof props.barWidth === 'string' && !isNaN(parseFloat(props.barWidth))
      ? parseFloat(props.barWidth)
      : 50;
  chartConfig.value.customOption = typeof props.customOption === 'object' && props.customOption !== null
    ? JSON.stringify(props.customOption, null, 2)
    : typeof props.customOption === 'string'
      ? props.customOption
      : '';
});
</script>
  
<style scoped>
.option-panel {
    width: 100%;
    height: 100%;
    background: var(--art-main-bg-color);
}

.config-tabs {
    height: 100%;
}

.config-section {
    padding: 16px 0;
}

.color-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.demo-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.data-tip {
    margin-top: 10px;
    font-size: 12px;
    color: #909399;
}

.example-format {
    margin-top: 5px;
    font-size: 11px;
    color: #606266;
    white-space: pre-wrap; /* Preserve line breaks */
    word-break: break-all; /* Break long words */
}

:deep(.el-tabs__content) {
    height: calc(100% - 40px);
    overflow-y: auto;
}

:deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-textarea__inner) {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 12px;
}
</style>
  